package com.skycong.hello77.common.viewpager;

import android.content.Context;
import android.graphics.PointF;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Created by Kiki on 2018/6/21.
 */

public class MyViewPager extends ViewPager {
    public void setScrollAble(boolean scrollAble) {
        this.scrollAble = scrollAble;
    }

    private boolean scrollAble = true;
    /**
     * 触摸时按下的点
     **/
    PointF downP = new PointF();
    /**
     * 触摸时当前的点
     **/
    PointF curP = new PointF();

    public MyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent arg0) {
        // TODO Auto-generated method stub
        // 当拦截触摸事件到达此位置的时候，返回true，
        // 说明将onTouch拦截在此控件，进而执行此控件的onTouchEvent
        if (scrollAble) {
            return super.onInterceptTouchEvent(arg0);
        } else {
            return false;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        /*curP.x = ev.getX();
        curP.y = ev.getY();
        int i = ev.getAction();
        if (i == MotionEvent.ACTION_DOWN) {
            downP.x = ev.getX();
            downP.y = ev.getY();
            getParent().requestDisallowInterceptTouchEvent(false);

        } else if (i == MotionEvent.ACTION_MOVE) {
            if (Math.abs(ev.getX() - downP.x) > Math.abs(ev.getY() - downP.y)) {
                getParent().requestDisallowInterceptTouchEvent(false);
            } else {
                getParent().requestDisallowInterceptTouchEvent(true);
            }

        } else if (i == MotionEvent.ACTION_UP) {
            if (downP.x == curP.x && downP.y == curP.y) {
                if (onViewPagerClickListener != null) {
                    onViewPagerClickListener.onViewPagerClick();
                }
            }

        } else if (i == MotionEvent.ACTION_CANCEL) {
            if (Math.abs(ev.getX() - downP.x) > Math.abs(ev.getY() - downP.y)) {
                getParent().requestDisallowInterceptTouchEvent(false);
            } else {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
        }
        return super.onTouchEvent(ev);*/
        if (scrollAble)
            return super.onTouchEvent(ev);
        else
            return false;
    }

    public void setOnViewPagerClickListener(OnViewPagerClickListener onViewPagerClickListener) {
        this.onViewPagerClickListener = onViewPagerClickListener;
    }

    private OnViewPagerClickListener onViewPagerClickListener;

    public interface OnViewPagerClickListener {
        void onViewPagerClick();
    }

}

